package com.wuyu.acl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuyu.acl.common.Result;
import com.wuyu.acl.po.RolePermission;
import com.wuyu.acl.service.RolePermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "角色权限管理")
@RestController
@RequestMapping("/admin/acl/role_permission")
public class RolePermissionController {

    @Resource
    private RolePermissionService rolePermissionService;


    /**
     * 角色权限管理：通过角色id查询权限ids
     *
     * @param roleId
     * @return
     */
    @Operation(summary = "通过角色id查询权限ids")
    @GetMapping("/{roleId}")
    public Result getPermissionListByRoleId(@PathVariable("roleId") Long roleId) {
        List<RolePermission> rolePermissionList = rolePermissionService.list(new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getRoleId, roleId));
        List<Long> ids = rolePermissionList.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        return Result.ok(ids);
    }

    /**
     * 角色权限管理：添加角色权限记录
     * @param roleId
     * @param permissionIds
     * @return
     */
    @Operation(summary = "添加角色权限记录")
    @PostMapping("/{roleId}")
    public Result add(@PathVariable("roleId") Long roleId,
                      @RequestBody List<Long> permissionIds) {
        // 1. 删除该角色原本的权限
        rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getRoleId, roleId));
        // 2. 添加角色新分配的权限
        List<RolePermission> rolePermissionList = permissionIds.stream().map(permissionId -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            return rolePermission;
        }).collect(Collectors.toList());
        rolePermissionService.saveBatch(rolePermissionList);
        return Result.ok();
    }
}
